package common.db.jdbc;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

import core.config.Factory;
import core.exception.PhysicalException;
import core.exception.ThrowableUtil;

/**
 * Jdbcクラス
 * @author Tadashi Nakayama
 */
public final class Jdbc implements Connection {

	/** コネクション */
	private final Connection conn;

	/**
	 * コンストラクタ
	 * @param val コネクション
	 */
	private Jdbc(final Connection val) {
		this.conn = val;
	}

	/**
	 * ラップ
	 * @param conn コネクション
	 * @return Jdbc
	 */
	public static Jdbc wrap(final Connection conn) {
		if (Jdbc.class.isInstance(conn)) {
			return Jdbc.class.cast(conn);
		}
		return new Jdbc(conn);
	}

	/**
	 * @see java.sql.Wrapper#unwrap(java.lang.Class)
	 */
	@Override
	public <T> T unwrap(final Class<T> iface) throws SQLException {
		return this.conn.unwrap(iface);
	}

	/**
	 * @see java.sql.Wrapper#isWrapperFor(java.lang.Class)
	 */
	@Override
	public boolean isWrapperFor(final Class<?> iface) throws SQLException {
		return this.conn.isWrapperFor(iface);
	}

	/**
	 * @see java.sql.Connection#createStatement()
	 */
	@Override
	public Statement createStatement() throws SQLException {
		return this.conn.createStatement();
	}

	/**
	 * @see java.sql.Connection#prepareStatement(java.lang.String)
	 */
	@Override
	public PreparedStatement prepareStatement(final String sql) throws SQLException {
		Method mt = Factory.getMethod(Connection.class, "prepareStatement", String.class);
		return prepareStatement(this.conn, mt, sql);
	}

	/**
	 * @see java.sql.Connection#prepareCall(java.lang.String)
	 */
	@Override
	public CallableStatement prepareCall(final String sql) throws SQLException {
		return this.conn.prepareCall(sql);
	}

	/**
	 * @see java.sql.Connection#nativeSQL(java.lang.String)
	 */
	@Override
	public String nativeSQL(final String sql) throws SQLException {
		return this.conn.nativeSQL(sql);
	}

	/**
	 * @see java.sql.Connection#setAutoCommit(boolean)
	 */
	@Override
	public void setAutoCommit(final boolean autoCommit) throws SQLException {
		this.conn.setAutoCommit(autoCommit);
	}

	/**
	 * @see java.sql.Connection#getAutoCommit()
	 */
	@Override
	public boolean getAutoCommit() throws SQLException {
		return this.conn.getAutoCommit();
	}

	/**
	 * @see java.sql.Connection#commit()
	 */
	@Override
	public void commit() throws SQLException {
		this.conn.commit();
	}

	/**
	 * @see java.sql.Connection#rollback()
	 */
	@Override
	public void rollback() throws SQLException {
		this.conn.rollback();
	}

	/**
	 * @see java.sql.Connection#close()
	 */
	@Override
	public void close() {
		try {
			this.conn.close();
		} catch (final SQLException ex) {
			ThrowableUtil.warn(ex);
		}
	}

	/**
	 * @see java.sql.Connection#isClosed()
	 */
	@Override
	public boolean isClosed() throws SQLException {
		return this.conn.isClosed();
	}

	/**
	 * @see java.sql.Connection#getMetaData()
	 */
	@Override
	public DatabaseMetaData getMetaData() throws SQLException {
		return this.conn.getMetaData();
	}

	/**
	 * @see java.sql.Connection#setReadOnly(boolean)
	 */
	@Override
	public void setReadOnly(final boolean readOnly) throws SQLException {
		this.conn.setReadOnly(readOnly);
	}

	/**
	 * @see java.sql.Connection#isReadOnly()
	 */
	@Override
	public boolean isReadOnly() throws SQLException {
		return this.conn.isReadOnly();
	}

	/**
	 * @see java.sql.Connection#setCatalog(java.lang.String)
	 */
	@Override
	public void setCatalog(final String catalog) throws SQLException {
		this.conn.setCatalog(catalog);
	}

	/**
	 * @see java.sql.Connection#getCatalog()
	 */
	@Override
	public String getCatalog() throws SQLException {
		return this.conn.getCatalog();
	}

	/**
	 * @see java.sql.Connection#setTransactionIsolation(int)
	 */
	@Override
	public void setTransactionIsolation(final int level) throws SQLException {
		this.conn.setTransactionIsolation(level);
	}

	/**
	 * @see java.sql.Connection#getTransactionIsolation()
	 */
	@Override
	public int getTransactionIsolation() throws SQLException {
		return this.conn.getTransactionIsolation();
	}

	/**
	 * @see java.sql.Connection#getWarnings()
	 */
	@Override
	public SQLWarning getWarnings() throws SQLException {
		return this.conn.getWarnings();
	}

	/**
	 * @see java.sql.Connection#clearWarnings()
	 */
	@Override
	public void clearWarnings() throws SQLException {
		this.conn.clearWarnings();
	}

	/**
	 * @see java.sql.Connection#createStatement(int, int)
	 */
	@Override
	public Statement createStatement(
					final int resultSetType, final int resultSetConcurrency) throws SQLException {
		return this.conn.createStatement(resultSetType, resultSetConcurrency);
	}

	/**
	 * @see java.sql.Connection#prepareStatement(java.lang.String, int, int)
	 */
	@Override
	public PreparedStatement prepareStatement(final String sql, final int resultSetType,
					final int resultSetConcurrency) throws SQLException {
		Method mt = Factory.getMethod(
						Connection.class, "prepareStatement", String.class, int.class, int.class);
		return prepareStatement(this.conn, mt, sql,
				Integer.valueOf(resultSetType), Integer.valueOf(resultSetConcurrency));
	}

	/**
	 * @see java.sql.Connection#prepareCall(java.lang.String, int, int)
	 */
	@Override
	public CallableStatement prepareCall(final String sql, final int resultSetType,
					final int resultSetConcurrency) throws SQLException {
		return this.conn.prepareCall(sql, resultSetType, resultSetConcurrency);
	}

	/**
	 * @see java.sql.Connection#getTypeMap()
	 */
	@Override
	public Map<String, Class<?>> getTypeMap() throws SQLException {
		return this.conn.getTypeMap();
	}

	/**
	 * @see java.sql.Connection#setTypeMap(java.util.Map)
	 */
	@Override
	public void setTypeMap(final Map<String, Class<?>> map) throws SQLException {
		this.conn.setTypeMap(map);
	}

	/**
	 * @see java.sql.Connection#setHoldability(int)
	 */
	@Override
	public void setHoldability(final int holdability) throws SQLException {
		this.conn.setHoldability(holdability);
	}

	/**
	 * @see java.sql.Connection#getHoldability()
	 */
	@Override
	public int getHoldability() throws SQLException {
		return this.conn.getHoldability();
	}

	/**
	 * @see java.sql.Connection#setSavepoint()
	 */
	@Override
	public Savepoint setSavepoint() throws SQLException {
		return this.conn.setSavepoint();
	}

	/**
	 * @see java.sql.Connection#setSavepoint(java.lang.String)
	 */
	@Override
	public Savepoint setSavepoint(final String name) throws SQLException {
		return this.conn.setSavepoint(name);
	}

	/**
	 * @see java.sql.Connection#rollback(java.sql.Savepoint)
	 */
	@Override
	public void rollback(final Savepoint savepoint) throws SQLException {
		this.conn.rollback(savepoint);
	}

	/**
	 * @see java.sql.Connection#releaseSavepoint(java.sql.Savepoint)
	 */
	@Override
	public void releaseSavepoint(final Savepoint savepoint) throws SQLException {
		this.conn.releaseSavepoint(savepoint);
	}

	/**
	 * @see java.sql.Connection#createStatement(int, int, int)
	 */
	@Override
	public Statement createStatement(final int resultSetType, final int resultSetConcurrency,
					final int resultSetHoldability) throws SQLException {
		return this.conn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
	}

	/**
	 * @see java.sql.Connection#prepareStatement(java.lang.String, int, int, int)
	 */
	@Override
	public PreparedStatement prepareStatement(final String sql, final int resultSetType,
					final int resultSetConcurrency, final int resultSetHoldability)
							throws SQLException {
		Method mt = Factory.getMethod(Connection.class, "prepareStatement",
						String.class, int.class, int.class, int.class);
		return prepareStatement(this.conn, mt, sql, Integer.valueOf(resultSetType),
				Integer.valueOf(resultSetConcurrency), Integer.valueOf(resultSetHoldability));
	}

	/**
	 * @see java.sql.Connection#prepareCall(java.lang.String, int, int, int)
	 */
	@Override
	public CallableStatement prepareCall(final String sql, final int resultSetType,
					final int resultSetConcurrency, final int resultSetHoldability)
							throws SQLException {
		return this.conn.prepareCall(
				sql, resultSetType, resultSetConcurrency, resultSetHoldability);
	}

	/**
	 * @see java.sql.Connection#prepareStatement(java.lang.String, int)
	 */
	@Override
	public PreparedStatement prepareStatement(
					final String sql, final int autoGeneratedKeys) throws SQLException {
		Method mt = Factory.getMethod(
						Connection.class, "prepareStatement", String.class, int.class);
		return prepareStatement(this.conn, mt, sql, Integer.valueOf(autoGeneratedKeys));
	}

	/**
	 * @see java.sql.Connection#prepareStatement(java.lang.String, int[])
	 */
	@Override
	public PreparedStatement prepareStatement(
					final String sql, final int[] columnIndexes) throws SQLException {
		Method mt = Factory.getMethod(
						Connection.class, "prepareStatement", String.class, int[].class);
		return prepareStatement(this.conn, mt, sql, columnIndexes);
	}

	/**
	 * @see java.sql.Connection#prepareStatement(java.lang.String, java.lang.String[])
	 */
	@Override
	public PreparedStatement prepareStatement(
					final String sql, final String[] columnNames) throws SQLException {
		Method mt = Factory.getMethod(
						Connection.class, "prepareStatement", String.class, String[].class);
		return prepareStatement(this.conn, mt, sql, columnNames);
	}

	/**
	 * @see java.sql.Connection#createClob()
	 */
	@Override
	public Clob createClob() throws SQLException {
		return this.conn.createClob();
	}

	/**
	 * @see java.sql.Connection#createBlob()
	 */
	@Override
	public Blob createBlob() throws SQLException {
		return this.conn.createBlob();
	}

	/**
	 * @see java.sql.Connection#createNClob()
	 */
	@Override
	public NClob createNClob() throws SQLException {
		return this.conn.createNClob();
	}

	/**
	 * @see java.sql.Connection#createSQLXML()
	 */
	@Override
	public SQLXML createSQLXML() throws SQLException {
		return this.conn.createSQLXML();
	}

	/**
	 * @see java.sql.Connection#isValid(int)
	 */
	@Override
	public boolean isValid(final int timeout) throws SQLException {
		return this.conn.isValid(timeout);
	}

	/**
	 * @see java.sql.Connection#setClientInfo(java.lang.String, java.lang.String)
	 */
	@Override
	public void setClientInfo(final String name, final String value) throws SQLClientInfoException {
		this.conn.setClientInfo(name, value);
	}

	/**
	 * @see java.sql.Connection#setClientInfo(java.util.Properties)
	 */
	@Override
	public void setClientInfo(final Properties properties) throws SQLClientInfoException {
		this.conn.setClientInfo(properties);
	}

	/**
	 * @see java.sql.Connection#getClientInfo(java.lang.String)
	 */
	@Override
	public String getClientInfo(final String name) throws SQLException {
		return this.conn.getClientInfo(name);
	}

	/**
	 * @see java.sql.Connection#getClientInfo()
	 */
	@Override
	public Properties getClientInfo() throws SQLException {
		return this.conn.getClientInfo();
	}

	/**
	 * @see java.sql.Connection#createArrayOf(java.lang.String, java.lang.Object[])
	 */
	@Override
	public Array createArrayOf(final String typeName, final Object[] elements) throws SQLException {
		return this.conn.createArrayOf(typeName, elements);
	}

	/**
	 * @see java.sql.Connection#createStruct(java.lang.String, java.lang.Object[])
	 */
	@Override
	public Struct createStruct(
					final String typeName, final Object[] attributes) throws SQLException {
		return this.conn.createStruct(typeName, attributes);
	}

	/**
	 * @see java.sql.Connection#setSchema(java.lang.String)
	 */
	@Override
	public void setSchema(final String schema) throws SQLException {
		this.conn.setSchema(schema);
	}

	/**
	 * @see java.sql.Connection#getSchema()
	 */
	@Override
	public String getSchema() throws SQLException {
		return this.conn.getSchema();
	}

	/**
	 * @see java.sql.Connection#abort(java.util.concurrent.Executor)
	 */
	@Override
	public void abort(final Executor executor) throws SQLException {
		this.conn.abort(executor);
	}

	/**
	 * @see java.sql.Connection#setNetworkTimeout(java.util.concurrent.Executor, int)
	 */
	@Override
	public void setNetworkTimeout(
					final Executor executor, final int milliseconds) throws SQLException {
		this.conn.setNetworkTimeout(executor, milliseconds);
	}

	/**
	 * @see java.sql.Connection#getNetworkTimeout()
	 */
	@Override
	public int getNetworkTimeout() throws SQLException {
		return this.conn.getNetworkTimeout();
	}

	/**
	 * プリペアステートメント（読込用）
	 *
	 * @param query SQL文
	 * @return プリペアステートメント
	 * @throws SQLException SQL例外
	 */
	public PreparedStatement readonlyStatement(final String query) throws SQLException {
		Method mt = Factory.getMethod(
						Connection.class, "prepareStatement", String.class, int.class, int.class);
		return prepareStatement(this.conn, mt, query,
				Integer.valueOf(ResultSet.TYPE_FORWARD_ONLY),
				Integer.valueOf(ResultSet.CONCUR_READ_ONLY));
	}

	/**
	 * PreparedStatement作成
	 * @param conn Connection
	 * @param mt PreparedStatement作成メソッド
	 * @param args 引数
	 * @return PreparedStatement
	 * @throws SQLException SQL例外
	 */
	private static PreparedStatement prepareStatement(final Connection conn,
					final Method mt, final Object... args) throws SQLException {
		try {
			if (conn != null && mt != null) {
				return PreparedStatement.class.cast(mt.invoke(conn, args));
			}
			return null;
		} catch (final InvocationTargetException ex) {
			Throwable th = ex.getCause();
			if (SQLException.class.isInstance(th)) {
				throw SQLException.class.cast(th);
			}
			throw new PhysicalException(th);
		} catch (final IllegalAccessException ex) {
			throw new PhysicalException(ex);
		}
	}
}
